package com.xyxy.platform.openapi.common.schedule;

import com.xyxy.platform.modules.core.file.SystemFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;

/**
 * 简介: 临时文件清理, 指定某个时间点, 如每天的凌晨1点开始执行. 根据文件的最后修改时间.
 *
 * @author Caizhenegda
 * @version 1.0
 * @Date 2015-12-28 21:57
 */
@Component
@Lazy(false)
public class TmpFileClearJob {

    @Autowired
    private SystemFileService systemFile;

    /**
     * 任务删除3小时前临时文件
     */
    long clearImageTime = 1000 * 60 * 60 * 3;

    protected static final Logger logger = LoggerFactory.getLogger(TmpFileClearJob.class);

    //@Scheduled(cron = "0/5 * *  * * ? ")   //每5秒执行一次
    //@Scheduled(cron="0 0/5 *  * * ? ")   //每5分钟执行一次
    @Scheduled(cron = "0 0 1 * * ?")   //每天凌晨1:00运行一次
    public void run() {
        logger.debug("开始清理临时文件!!");
        File tmpFileDir = new File(systemFile.getTmpFilePath());
        if (!tmpFileDir.exists()) {
            logger.info("tmp file dir not exist, init and create...!");
            tmpFileDir.mkdirs();
        }
        if (!tmpFileDir.isDirectory()) {
            logger.info("tmp file dir not a directory");
            return;
        }
        File[] subFiles = tmpFileDir.listFiles();
        if (subFiles == null) {
            logger.info("subFiles isEmpty");
            return;
        }
        long currTime = System.currentTimeMillis();
        for (File tmpFile : subFiles) {
            long lastModified = tmpFile.lastModified();
            if (currTime - lastModified > clearImageTime) {
                tmpFile.delete();
            }
        }
    }

}
